package com.hy.schedule.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * author: Mr.Du
 * Date: 2023/6/9
 * Time: 13:53
 */
@Configuration
public class TaskSchedulerConfig {
    
    // 用来存入线程执行情况, 方便于停止定时任务时使用
    public static Map<Long, ScheduledFuture> cacheMap= new ConcurrentHashMap<>();
    
    @Lazy
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler1(){
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    
        // 配置 ThreadPoolTaskScheduler 的属性
        scheduler.setPoolSize(3); // 设置线程池大小
        scheduler.setThreadNamePrefix("my-scheduler1-"); // 设置线程名称前缀
    
        scheduler.setAwaitTerminationSeconds(60);         // 等待时长
        scheduler.setWaitForTasksToCompleteOnShutdown(true);  // 调度器shutdown被调用时等待当前被调度的任务完成
        return scheduler;
    }
    
    @Lazy
    @Bean
    @Primary
    public ThreadPoolTaskScheduler threadPoolTaskScheduler2(){
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        
        // 配置 ThreadPoolTaskScheduler 的属性
        scheduler.setPoolSize(5); // 设置线程池大小
        scheduler.setThreadNamePrefix("my-scheduler2-"); // 设置线程名称前缀
        
        scheduler.setAwaitTerminationSeconds(60);         // 等待时长
        scheduler.setWaitForTasksToCompleteOnShutdown(true);  // 调度器shutdown被调用时等待当前被调度的任务完成
        return scheduler;
    }
}
